
import { prisma } from "@/lib/db";
import { handlerApi } from "@/lib/handlerApi";
import { Menu } from "@prisma/client";
import { cookies } from "next/headers";
import { NextRequest, NextResponse } from "next/server";
const getAllMenus = async (ids: number[]) => {
  const menuList = await prisma.menu.findMany({});
  const list: Menu[] = [];
  const getIds = (menuId: number[]) => {
    let parentId: number[] = [];
    menuList.forEach((it) => {
      const listIds = list.map((it) => it.id);
      if (menuId.includes(it.id)) {
        if (!listIds.includes(it.id)) {
          list.push(it);
        }
        if (it.parentId) {
          parentId.push(it.parentId);
        }
      }
    });
    if (parentId.length > 0) {
      getIds(parentId);
    }
  };
  getIds(ids);
  return list;
};
/**
 * 获取菜单信息
 * @param roleId 角色id
 * @returns
 */
const getMenus = async (roleId: number) => {
  const result = await prisma.role.findUnique({
    where: {
      id: roleId,
    },
    select: {
      menuList: true,
    },
  });
  let menusId = [];
  if (result?.menuList) {
    menusId = JSON.parse(result.menuList);
  }
  const menuList = await getAllMenus(menusId);
  return menuList;
};
/**
 *
 * @param roleIds 角色的所有id
 * @returns 获取角色的详细信息
 */
const getRoleList = async (roleIds: number[]) => {
  const roleList = await prisma.role.findMany({
    where: {
      id: {
        in: roleIds,
      },
    },
  });
  return roleList;
};
const getUserInfo = handlerApi(async (req: NextRequest) => {
  const cookieStore = await cookies();
  const id = cookieStore.get("userId")?.value || 0;
  let userId = Number(id);
  const userInfo = await prisma.user.findUnique({
    where: {
      id: userId,
    },
  });
  if (userInfo) {
    let info: any = {
      ...userInfo,
    };
    let { currentRole, roleList } = userInfo;
    if (roleList) {
      const roleObj = await getRoleList(JSON.parse(roleList));
      info.roles = roleObj;
    }
    if (!currentRole) {
      if (roleList && roleList.length > 0) {
        roleList = JSON.parse(roleList) || [];
        if (roleList?.length == 0) {
          throw new Error("没有权限");
        }
        currentRole = Number(roleList![0]);
        await prisma.user.update({
          where: {
            id: userId,
          },
          data: {
            currentRole,
          },
        });

        let menus = await getMenus(currentRole);
        info.menus = menus;
      } else {
        throw new Error("没有权限");
      }
    } else {
      let menus = await getMenus(currentRole);
      info.menus = menus;
    }
    info.currentRole = currentRole;
    return info;
  }
  throw new Error("没有权限");
});
export const GET = getUserInfo;
export const dynamic = "force-dynamic";
